package com.itheima.health.config;


import com.itheima.health.security.HealthUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author 十一
 * @Description
 * @create 2020-11-13-19:41
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties(JwtProperties.class)
public class HealthWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private HealthUserDetailServiceImpl healthUserDetailService;

    @Autowired
    private JwtProperties properties;
    //生成密码的密文
    public static void main(String[] args) {
        System.out.println(passwordEncoder().encode("admin"));
    }

    /**
     * 用于配置用户登录信息，如用户名，密码
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据库版
        auth.userDetailsService(healthUserDetailService).passwordEncoder(passwordEncoder());

        /*//内存版security
        auth.inMemoryAuthentication()
                .withUser("admin").password(passwordEncoder().encode("123")).roles("ADMIN")
                .and()
                .withUser("jack").password(passwordEncoder().encode("123")).roles("ADMIN","USER","QUERY");*/
    }

    /**
     * 配置可匿民访问的资源
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        //web.ignoring().mvcMatchers("/js/**","/css/**","/login.html");
    }

    /**
     *配置指定的登录、登出、友好等界面以及配置界面的访问权限
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()  //以下为配置重写的过滤器
                .addFilter(new JWTAuthenticationFilter(super.authenticationManager(),properties))//配置进行认证的过滤器
                .addFilter(new JWTAuthorizationFilter(super.authenticationManager(),properties))//配置进行获取权限的过滤器
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS); //禁用security自带的session
        /*//前端界面的表单action属性值必须为：/login
        //表单的账号密码name属性默认必须为：username，password
        //需要修该需重写usernameParameter、passwordParameter过滤器

         http.formLogin().loginPage("/login.html")
                 .loginProcessingUrl("/login.do")  //重写过滤器  UsernamePasswordAuthenticationFilter 处理登录请求地址
                 .defaultSuccessUrl("/pages/index.html",false)  //认证成功跳转，失败不跳转
                 .failureUrl("/login.html")  //失败跳转界面
                 .and().authorizeRequests()// 配置被访问界面的权限
                 .antMatchers("/pages/delete.html").hasRole("ADMIN")  //   拥有 ADMIN角色 采用可以访问 delete.html
                 .antMatchers("/pages/query.html").hasRole("QUERY")
                 .antMatchers("/pages/**").authenticated() //  只需要认证即可访问
                 .and().exceptionHandling().accessDeniedPage("/error.html")//跳转友好界面
                 .and().logout().logoutUrl("/logout.do").logoutSuccessUrl("/login.html").invalidateHttpSession(true)
                 .and().csrf().disable();  //禁用crsf过滤器，token  令牌校验*/
    }

    @Bean
    public static PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
